@<template>
  <div id="chart"></div>
</template>

<script>
import * as d3 from "d3";
export default {
  data() {
    return {
      data: [],
      xScale: null,
      yScale: null,
      line: null,
      svg: null,
      width: 800,
      height: 400,
            margin: {
        top: 20,
        right: 20,
        bottom: 40,
        left: 40,
      }, // 图表边距
    };
  },
  mounted() {
    // 初始化画布
    this.svg = d3
      .select("#chart")
      .append("svg")
      .attr("width", this.width)
      .attr("height", this.height)
      .append("g")
      .attr("transform", `translate(${this.margin.left},${this.margin.top})`);

    // 定义x、y轴比例尺
    this.xScale = d3
      .scaleTime()
      .range([0, this.width - this.margin.left - this.margin.right]);
    this.yScale = d3
      .scaleLinear()
      .range([this.height - this.margin.top - this.margin.bottom, 0]);

    // 定义x、y轴标尺
    const xAxis = d3.axisBottom(this.xScale);
    const yAxis = d3.axisLeft(this.yScale);

    // 添加x、y轴
    this.svg
      .append("g")
      .attr("class", "x axis")
      .attr("transform", `translate(0,${this.height - this.margin.top - this.margin.bottom})`)
      .call(xAxis);
    this.svg
      .append("g")
      .attr("class", "y axis")
      .call(yAxis);

    // 定义折线
    this.line = d3
      .line()
      .x((d) => this.xScale(d.time))
      .y((d) => this.yScale(d.value))
      .curve(d3.curveMonotoneX);

            // 创建折线路径元素
      this.path = this.svg
        .append("path")
        .datum(this.data)
        .attr("stroke", "red")
        .attr("fill", "transparent")
        .attr("class", "line")
        .attr("d", this.line);
  },
  methods: {
    // 更新数据
    updateData(newData) {
      this.data = newData;

      // 更新比例尺
      this.xScale.domain(d3.extent(this.data, (d) => d.time));
      this.yScale.domain([0, 1]);

      // 更新x、y轴标尺
      this.svg.select(".x.axis").call(d3.axisBottom(this.xScale).tickFormat(d3.timeFormat("%H:%M:%S")));
      this.svg.select(".y.axis").call(d3.axisLeft(this.yScale));

      // // 绘制折线
      // this.svg
      //   .select(".line")
      //   .datum(this.data)
      //   .attr("class", "line")
      //   .attr("d", this.line);
      this.path.datum(this.data).attr("d", this.line);

    },
  },
  created() {
    // 模拟数据
    setInterval(() => {
      const time = new Date();
      const value = Math.random();
      const newData = [...this.data, { time, value }];
      this.updateData(newData);
      console.log(newData)
    }, 1000);
  },
};
</script>

<style>
.axis path,
.axis line {
  fill: none;
  stroke: #ccc;
  stroke-width: 1px;
  shape-rendering: crispEdges;
}

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}
</style>